$(function() {

    executeAllFn();

    //执行所有的方法
    function executeAllFn() {
        //添加标签
        $('.bilibili-player-video-bottom-area').prepend(`
    <div class='myDiv'>
    <button class='myButton' id='mark' title='快捷键Alt' >标&#12288;记</button>
    <button class='myButton' id='clearMark' >消除标记</button>
    <button class='myButton' id='pre' title='快捷键A' >上一句</button>
    <button class='myButton' id='after' title='快捷键D' >下一句</button>
    <button class='myButton' id='learn' title='快捷吗Ctrl'>这句听不懂</button>
    <button class='myButton' id='clearLoop' >消除循环</button>
    <button class='myButton' id='orderLoop' >顺序循环播放所有听不懂句子</button>
    <button class='myButton' id='randomLoop'>随机循环播放所有听不懂句子</button>
    <button class='myButton' id='randomAllLoop'>随机循环播放所有句子</button>
    <button class='myButton' id='money'>打赏</button>
    </div>
    `)
            /**<img  class='myImg' src='https://i0.hdslb.com/bfs/album/3eb13efd0a1150845b7ed04f81921abe83e9677a.png@151w_150h_1c.webp'/>  */

        $('.bilibili-player-video-bottom-area').prepend(`
    <div class='notUnderstandDiv'> 
   
    </div>
    `)

        //登待弹框的图片
        $('body').append(`

        <div>
        <img src="https://i0.hdslb.com/bfs/album/3eb13efd0a1150845b7ed04f81921abe83e9677a.png@151w_150h_1c.webp" id="min_img" style="width:500px;height:400px;display:none">
    </div>
    <div id="outerdiv" style="position:fixed;top:0;left:0;background:rgba(0,0,0,0.7);z-index:99999;width:100%;height:100%;display:none;">
        <div id="innerdiv" style="position:absolute;">
            <img id="max_img" style="border:5px solid #fff;" src="" />
            <img style='width:162px' src='http://home.zouchangfu.top:3000/1.png'/>
        </div>
    </div>
`)


        //获取视频对象
        var videoElement = $('[preload="auto"]')[0]
        var arr = []
        var url = location.href;
        var key;
        var currentSentenceTime;
        var notUnderstandArr = [];
        var flagSleep = false; //记录睡眠递归状态
        var flagSleep2 = false; //记录睡眠递归状态
        var flagSleep3 = false; //记录睡眠递归状态


        //解析路径
        if (url.indexOf('t=') != -1) {
            if (url.indexOf('&') != -1) {
                let temp = url.substring(url.indexOf('t='), url.indexOf('&') + 1)
                console.info("tempUrl:", temp)
                url = url.replace(temp, '')
            } else {
                url = url.substring(0, url.indexOf('t=') - 1)
                console.info('tempUrl===', url)
            }


        }
        if (url.indexOf('spm_id_from') != -1) {
            let start = url.indexOf('video')
            let end = url.indexOf('?')
            key = url.substring(start + 6, end)
        } else {
            let start = url.indexOf('video')
            key = url.substring(start + 6).trim()
        }
        console.info('key:', key)


        //获取出被标记的数组
        var data = localStorage.getItem(key)
        console.info('标记的数组', data)
        if (data) {
            arr = JSON.parse(data)
            $('#mark').html('标记' + '(' + arr.length + ')')
            console.info('已经获取到标记的时间', arr)
        } else {
            //如果没有获取到标记句子
            if (arr.length == 0) {
                $('#clearMark').html('未被标记')
            }
        }




        //标记
        function mark() {
            var time = videoElement.currentTime
            arr.push(time)
            $('#mark').html('标记' + '(' + arr.length + ')')
            $('#clearMark').html('消除标记')
            console.log(arr)
            var text = JSON.stringify(arr)
            localStorage.setItem(key, text)
        }


        //消除标记
        function clearMark() {
            arr = []
            localStorage.removeItem(key)
            $('#clearMark').html('已经消除')
            $('#mark').html('标记')
        }

        //上一句
        function pre() {
            if (arr.length > 0) {
                arr.forEach((time, index) => {
                    let currentTime = videoElement.currentTime
                        //判断当前时间在哪个时间断,回到上一个开始的点
                    if (index != arr.length - 1 && currentTime > time && currentTime < arr[index + 1]) {
                        if (index != 0) {
                            videoElement.currentTime = arr[index - 1]
                        } else {
                            videoElement.currentTime = arr[0]
                        }
                    }

                })
            } else {
                sendNotification('还没标记句子哦,请先标记句子~(￣▽￣)~*');
            }
        }


        //下一句
        function after() {
            if (arr.length > 0) {
                arr.forEach((time, index) => {
                    let currentTime = videoElement.currentTime
                        //判断当前时间在哪个时间断,跳到下一个开始的点
                    if (index != arr.length - 1 && currentTime > time && currentTime < arr[index + 1]) {
                        videoElement.currentTime = arr[index + 1]
                    }
                })
            } else {
                sendNotification('还没标记句子哦,请先标记句子~(￣▽￣)~*');
            }
        }

        //点击:这句我听不懂,标记听不懂的句子
        function learn() {
            if (arr.length > 0) {

                var tempTime; //记录不懂句子的时间
                var nextTime; //记录不懂句子的下一个句子的时间
                var totalTime; //记录听不懂的总时间
                arr.forEach((time, index) => {
                    let currentTime = videoElement.currentTime
                    if (index != arr.length - 1 && currentTime >= time && currentTime <= arr[index + 1]) {
                        tempTime = arr[index]
                        nextTime = arr[index + 1]
                    }
                })

                //如果是第一句直接添加
                if (notUnderstandArr.length == 0) {
                    notUnderstandArr.push(tempTime)
                    $('.notUnderstandDiv').append(`
                    <button value='${tempTime}' class='notUnderstand' 
                    id='notUnderstand${notUnderstandArr.length}'>${notUnderstandArr.length}
                    </button> `)

                    //给按钮绑定事件
                    $(`#notUnderstand${notUnderstandArr.length}`).click(() => {
                        repeat(tempTime);
                    })

                    //长按3秒无限循环播放
                    var startTime;
                    var endTime;
                    $(`#notUnderstand${notUnderstandArr.length}`).mousedown(function() {
                        startTime = new Date().getTime();
                    });

                    $(`#notUnderstand${notUnderstandArr.length}`).mouseup(function() {
                        endTime = new Date().getTime();
                        let time = (endTime - startTime) / 1000
                        console.info('time:', time)
                        if (time >= 2) {
                            sendNotification(`开启循环句子[${notUnderstandArr.length}]`)
                            loopFn(tempTime, nextTime)
                        }
                    });



                    $('#learn').html('这句听不懂' + '(' + notUnderstandArr.length + ')')

                    //有可能获取到时同一句,同一句的话给予添加
                } else if (notUnderstandArr[notUnderstandArr.length - 1] != tempTime) {
                    notUnderstandArr.push(tempTime)
                    totalTime += tempTime
                    $('.notUnderstandDiv').append(`
                    <button value='${tempTime}' class='notUnderstand' 
                    id='notUnderstand${notUnderstandArr.length}'>${notUnderstandArr.length}
                    </button> `)

                    //给按钮绑定事件
                    $(`#notUnderstand${notUnderstandArr.length}`).click(() => {
                        repeat(tempTime);
                    })


                    //长按3秒无限循环播放
                    var startTime;
                    var endTime;
                    $(`#notUnderstand${notUnderstandArr.length}`).mousedown(function() {
                        startTime = new Date().getTime();
                    });

                    $(`#notUnderstand${notUnderstandArr.length}`).mouseup(function() {
                        endTime = new Date().getTime();
                        let time = (endTime - startTime) / 1000
                        console.info('time:', time)
                        if (time >= 2) {
                            sendNotification(`开启循环句子[${notUnderstandArr.length}]`)
                            loopFn(tempTime, nextTime)
                        }
                    });



                    $('#learn').html('这句听不懂' + '(' + notUnderstandArr.length + ')')
                }




            } else {
                sendNotification('还没标记句子哦,请先标记句子~(￣▽￣)~*');
            }
        }

        //重复听不懂的句子
        function repeat(notUnderstandTime) {
            // console.info('notUnderstandTime', notUnderstandTime)
            videoElement.currentTime = notUnderstandTime;
        }

        //顺序循环播放所有听不懂的句子,这里的代码太帅了
        var orderLoopIp;

        function orderLoop() {
            if (notUnderstandArr.length <= 1) {
                sendNotification('不懂的句子需要大于1哦!')
                return;
            }
            //先播放一次
            console.info('notUnderstandArr:', notUnderstandArr)
            var executeOrderLoopTime;
            var index = 0;
            videoElement.currentTime = notUnderstandArr[index];
            executeOrderLoopTime = (arr[index + 1] - notUnderstandArr[index]) * 1000
            console.info('executeOrderLoopTime', executeOrderLoopTime)
                //睡眠直到当前句子播放完毕
            async function sleep() {
                //停止循环
                if (flagSleep) {
                    flagSleep = false;
                    return;
                }
                await sleepMethod(executeOrderLoopTime);
                index++;
                if (index != notUnderstandArr.length) {
                    videoElement.currentTime = notUnderstandArr[index]
                    var currentArrIndex;
                    arr.forEach((item, arrIndex) => {
                        console.info(notUnderstandArr[index], '----', item)
                        if (notUnderstandArr[index] == item) {
                            currentArrIndex = arrIndex;
                        }
                    })
                    console.info('currentArrIndex', currentArrIndex)
                    if (currentArrIndex != arr.length - 1) {
                        executeOrderLoopTime = (arr[currentArrIndex + 1] - notUnderstandArr[index]) * 1000
                        console.info('executeOrderLoopTime', executeOrderLoopTime, notUnderstandArr[index], 'currentTime:', videoElement.currentTime)
                        sleep();
                    }
                } else {
                    orderLoop()
                }
            }
            sleep();
        }

        //随机循环播放不懂的句子
        function randomLoop() {
            if (notUnderstandArr.length <= 1) {
                sendNotification('不懂的句子需要大于1哦!')
                return;
            }
            //拷贝数组
            let newArr = JSON.stringify(notUnderstandArr)
            let newNotUnderstandArr = JSON.parse(newArr)
            newNotUnderstandArr.sort(function() {
                return Math.random() - 0.5
            });
            //先播放一次
            var executeOrderLoopTime;
            var index = 0;
            videoElement.currentTime = newNotUnderstandArr[index];
            executeOrderLoopTime = (arr[index + 1] - newNotUnderstandArr[index]) * 1000
            console.info('executeOrderLoopTime', executeOrderLoopTime)
                //睡眠直到当前句子播放完毕
            async function sleep() {
                if (flagSleep2) {
                    flagSleep2 = false;
                    return;
                }
                await sleepMethod(executeOrderLoopTime);
                index++;
                if (index != newNotUnderstandArr.length) {
                    videoElement.currentTime = newNotUnderstandArr[index]
                    var currentArrIndex;
                    arr.forEach((item, arrIndex) => {
                        console.info(newNotUnderstandArr[index], '----', item)
                        if (newNotUnderstandArr[index] == item) {
                            currentArrIndex = arrIndex;
                        }
                    })
                    console.info('currentArrIndex', currentArrIndex)
                    if (currentArrIndex != arr.length - 1) {
                        executeOrderLoopTime = (arr[currentArrIndex + 1] - newNotUnderstandArr[index]) * 1000
                        console.info('executeOrderLoopTime', executeOrderLoopTime, newNotUnderstandArr[index], 'currentTime:', videoElement.currentTime)
                        sleep();
                    }
                } else {
                    randomLoop()
                }
            }
            sleep();
        }

        //随机播放所有的句子
        function randomAllLoop() {
            //拷贝数组
            let newArr = JSON.stringify(arr)
            let randomArr = JSON.parse(newArr)
            randomArr.sort(function() {
                return Math.random() - 0.5
            });
            console.info('arr?:', arr)

            //先播放一次
            var executeOrderLoopTime;
            var index = 0;
            videoElement.currentTime = randomArr[index];
            executeOrderLoopTime = (arr[index + 1] - randomArr[index]) * 1000
            console.info('executeOrderLoopTime', executeOrderLoopTime)
                //睡眠直到当前句子播放完毕
            async function sleep() {
                if (flagSleep3) {
                    flagSleep3 = false;
                    return;
                }
                await sleepMethod(executeOrderLoopTime);
                index++;
                if (index != randomArr.length) {
                    videoElement.currentTime = randomArr[index]
                    var currentArrIndex;
                    arr.forEach((item, arrIndex) => {
                        console.info(randomArr[index], '----', item)
                        if (randomArr[index] == item) {
                            currentArrIndex = arrIndex;
                        }
                    })
                    console.info('currentArrIndex', currentArrIndex)
                    if (currentArrIndex != arr.length - 1) {
                        executeOrderLoopTime = (arr[currentArrIndex + 1] - randomArr[index]) * 1000
                        console.info('executeOrderLoopTime', executeOrderLoopTime, randomArr[index], 'currentTime:', videoElement.currentTime)
                        sleep();
                    } else {
                        randomAllLoop()
                    }
                } else {
                    randomAllLoop()
                }
            }
            sleep();
        }




        //无限循环 currentTime当前时间, nextTime下一句的时间
        var loopTimeId;

        function loopFn(currentTime, nextTime) {
            //第一次进来,执行一次
            repeat(currentTime)
            let executeTime = (nextTime - currentTime) * 1000;
            loopTimeId = setInterval(() => {
                console.info('executeTime:', executeTime)
                repeat(currentTime)
            }, executeTime)
        }

        //消除循环听不懂的句子
        function clearLoop(loopId) {
            if (loopId) {
                sendNotification('成功消除循环')
                clearInterval(loopId)
            }
        }

        //发通知
        function sendNotification(message) {
            chrome.runtime.sendMessage({ value: message }, function(response) {
                console.log(response);
            });
        }

        //睡眠方法
        function sleepMethod(ms) {
            return new Promise((resolve) => setTimeout(resolve, ms));
        }


        //弹框图片
        function imgShow(outerdiv, innerdiv, max_img) {
            $("#max_img").attr("src", 'https://i0.hdslb.com/bfs/album/3eb13efd0a1150845b7ed04f81921abe83e9677a.png@151w_150h_1c.webp');
            $("#min_img").attr("src", 'https://i0.hdslb.com/bfs/album/3eb13efd0a1150845b7ed04f81921abe83e9677a.png@151w_150h_1c.webp').load(function() {
                var windowW = $(window).width();
                var windowH = $(window).height();
                var realWidth = this.width;
                var realHeight = this.height;
                var imgWidth, imgHeight;
                var scale = 0.8;

                if (realHeight > windowH * scale) {
                    imgHeight = windowH * scale;
                    imgWidth = imgHeight / realHeight * realWidth;
                    if (imgWidth > windowW * scale) {
                        imgWidth = windowW * scale;
                    }
                } else if (realWidth > windowW * scale) {
                    imgWidth = windowW * scale;
                    imgHeight = imgWidth / realWidth * realHeight;
                } else {
                    imgWidth = realWidth;
                    imgHeight = realHeight;
                }
                $("#max_img").css("width", imgWidth);

                var w = (windowW - imgWidth) / 2;
                var h = (windowH - imgHeight) / 2;
                $(innerdiv).css({
                    "top": h,
                    "left": w
                });
                $(outerdiv).fadeIn("fast");
            });

            $(outerdiv).click(function() {
                $(this).fadeOut("fast");
            });
        }




        //标记
        $('#mark').click(() => {
            mark();
        })

        //消除标记
        $('#clearMark').click(() => {
            clearMark();
        })

        //上一句
        $('#pre').click(() => {
            pre();
        })

        //下一句
        $('#after').click(() => {
            after();
        })

        //点击:这句我听不懂,标记听不懂的句子
        $('#learn').click(() => {
            learn();
        })

        //重复听不懂的句子
        $('#repeat').click(() => {
            repeat();
        })

        //消除循环
        $('#clearLoop').click(() => {
            flagSleep = true;
            flagSleep2 = true;
            flagSleep3 = true;
            clearLoop(loopTimeId);
            clearLoop(orderLoopIp);
            loopTimeId = ''
            orderLoopIp = ''
        })

        $('#orderLoop').click(() => {
            orderLoop();
        })

        $('#randomLoop').click(() => {
            randomLoop();
        })

        $('#randomAllLoop').click(() => {
            randomAllLoop();
        })

        $('#money').click(() => {
            imgShow("#outerdiv", "#innerdiv", "#max_img");
        })



        document.onkeyup = function(event) { //键盘事件
            console.log('键位:', event.keyCode)
            var e = event || window.event || arguments.callee.caller.arguments[0];
            //按下A,上一句
            if (e && e.keyCode === 65) {
                pre();
                //按下B,下一句       
            } else if (e && e.keyCode === 68) {
                after();
                //按下Ctrl,表示标记听不懂的句子
            } else if (e && e.keyCode === 17) {
                learn();
            } else if (e && e.keyCode === 18) {
                mark();
            }
        };
    }

    //页面切换再次执行所有的方法
    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        //console.info('执行了:', request.value)
        executeAllFn();
        sendResponse('我执行了..')
    });



})